package com.qf.hospital.realm;

import com.alibaba.druid.util.StringUtils;
import com.qf.hospital.entity.SysUser;
import com.qf.hospital.enums.HospitalExceptionEnums;
import com.qf.hospital.exception.HospitalException;
import com.qf.hospital.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ASUS
 * @version V1.0
 * @Project hospital
 * @Package com.qf.hospital.realm
 * @Date 2021/10/15 10:54
 */
public class HospitalRealm extends AuthorizingRealm {

    public static final int HASH_ITERATIONS = 1024;

    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(HASH_ITERATIONS);
        this.setCredentialsMatcher(matcher);
    }

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String loginName = (String) authenticationToken.getPrincipal();

        SysUser sysUser = sysUserService.findByLoginName(loginName);
        if(sysUser == null){
            throw new HospitalException(HospitalExceptionEnums.USERNAME_PASSWORD_ERROR);
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser,sysUser.getPwd(),"HospitalRealm");
        info.setCredentialsSalt(ByteSource.Util.bytes(sysUser.getSalt()));
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


}
